import re

from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.paginator import Paginator
from django.http import JsonResponse
from django.shortcuts import render
from django.views import View

from courses.models import Course
from operation.models import UserMessage
from organization.models import CourseOrg, Teacher
from users.forms import UploadImageForm, UserInfoForm
from users.models import UserProfile
from utils import constant


# 用户中心
class UserInfoView(LoginRequiredMixin, View):
    def get(self, request):
        return render(request, 'usercenter-info.html')

    # 修改用户信息
    def post(self, request):
        user = request.user
        # 注意 1 queryDict是只读的; 2 前端传回的birthday可能是'2019年6月9日', 需要转换成'2016-6-9',才能通过表单认证
        data = request.POST.dict()
        data['birthday'] = re.sub('[年月日]', '-', data['birthday']).rstrip('-')
        # print(data['birthday'])
        userinfo_form = UserInfoForm(data)
        if userinfo_form.is_valid():
            nick_name = userinfo_form.cleaned_data['nick_name']
            gender = userinfo_form.cleaned_data['gender']
            birthday = userinfo_form.cleaned_data['birthday']
            address = userinfo_form.cleaned_data['address']
            mobile = userinfo_form.cleaned_data['mobile']
            try:
                UserProfile.objects.filter(username=user.username).update(
                    nick_name=nick_name,
                    gender=gender,
                    birthday=birthday,
                    address=address,
                    mobile=mobile,
                )
            except:
                return JsonResponse({"status": "error"})
            # 修改成功
            return JsonResponse({"status": "success"})
        else:
            # 修改失败
            return JsonResponse({"status": "error"})


# 修改用户头像
class UploadImageView(LoginRequiredMixin, View):
    def post(self, request):
        user = request.user
        upload_image_form = UploadImageForm(request.POST, request.FILES)  # 上传的是文件类型,post拿不到图片属性
        if upload_image_form.is_valid():
            image = upload_image_form.cleaned_data['image']
            try:
                user.image = image
                user.save()
                return JsonResponse({"status": "success", "msg": '头像修改成功'})
            except:
                return JsonResponse({"status": "error", "msg": '头像修改失败'})
        else:
            return JsonResponse({"status": "error", "msg": '头像修改失败'})


# 我的课程
class MyCourseView(LoginRequiredMixin, View):
    """用户点击我的课程，获取用户课程表(UserCourse)的数据返回"""
    def get(self, request):
        user = request.user
        user_courses = user.usercourse_set.order_by('-add_time')
        return render(request, 'usercenter-mycourse.html', {
            'user_courses': user_courses,
        })


# 我的收藏 课程学校
class MyFavOrgView(LoginRequiredMixin, View):
    def get(self, request):
        user = request.user
        # 所有课程id
        fav_id_lst = [fav.fav_id for fav in user.userfavorite_set.filter(fav_type=2).order_by('-add_time')]
        # 所有课程
        org_list = CourseOrg.objects.filter(id__in=fav_id_lst)

        return render(request, 'usercenter-fav-org.html', {'org_list': org_list})


# 我的收藏 授课教师
class MyFavTeacherView(LoginRequiredMixin, View):
    def get(self, request):
        user = request.user
        fav_id_lst = [fav.fav_id for fav in user.userfavorite_set.filter(fav_type=3).order_by('-add_time')]

        teacher_list = Teacher.objects.filter(id__in=fav_id_lst)

        return render(request, 'usercenter-fav-teacher.html', {'teacher_list': teacher_list})


# 我的收藏 公开课
class MyFavCourseView(LoginRequiredMixin, View):
    def get(self, request):
        user = request.user
        fav_id_lst = [fav.fav_id for fav in user.userfavorite_set.filter(fav_type=1).order_by('-add_time')]

        course_list = Course.objects.filter(id__in=fav_id_lst)

        return render(request, 'usercenter-fav-course.html', {'course_list': course_list,})


# 我的消息
class MyMessageView(LoginRequiredMixin, View):
    def get(self, request):
        # 需要进行分页返回
        next = request.GET.get('next', 1)
        user: UserProfile = request.user
        # 0 全局消息, id 私有消息
        messages = list(UserMessage.objects.filter(user__in=(0, user.id)).order_by('-add_time'))

        page_messages = Paginator(messages, constant.MESSAGE_PER_PAGE)
        total_page_nums = page_messages.num_pages

        # 如果页码不是整数类型, 或者页码小于0, 返回第一页
        try:
            next = int(next)
            assert next > 0
        except:
            next = 1
        # 如果页码大于最大页码, 返回最后一页
        next = total_page_nums if next > total_page_nums else next
        page_message = page_messages.page(next)
        # 给分页对象添加pages属性,用于页面渲染页码
        page_message.pages = range(1, page_messages.num_pages + 1)
        return render(request, 'usercenter-message.html', {
            'messages': page_message,
        })

